<?php
/**
 * 区域营销基金主线流程数据模型
 * @author Administrator
 *
 */
class areaProcessModel extends MY_Model{
    function areaProcessModel(){
        parent::MY_Model();
        $this->table = 'AreaProcess';
    }
    /**
     * 包装数据
     * @param array $list
     * @return Ambigous <string, unknown>
     */
    function packing($list = array()){
        //时间单位配置
        $this->CI->load->model('timeUnitModel');
        $timeUnitList = $this->CI->timeUnitModel->getCacheData('timeUnitList');
        //角色列表
        $roleList = $this->config->item('roleList');
        //审核结果
        $auditRs = $this->config->item('auditRs');
        foreach ($list as $k => $v){
            //时间单位
            $v['timeUnitStr'] = isset($timeUnitList[$v['year']][$v['timeUnit']]) ? $timeUnitList[$v['year']][$v['timeUnit']] : '';
            //预算审核状态
            $v['budgetAuditStr'] = isset($roleList[$v['budgetAuditRole']]) ? $roleList[$v['budgetAuditRole']].'已审核' : '';
            if ($v['budgetAuditStr']){
                $v['budgetAuditStr'] .= isset($auditRs[$v['budgetAuditRs']]) ? ','.$auditRs[$v['budgetAuditRs']] : '';
            }else{
                $v['budgetAuditStr'] = isset($auditRs[$v['budgetAuditRs']]) ? $auditRs[$v['budgetAuditRs']] : '';
            }
            //结算审核状态
            $v['settleAuditStr'] = isset($roleList[$v['settleAuditRole']]) ? $roleList[$v['settleAuditRole']].'已审核' : '';
            if ($v['settleAuditStr']){
                $v['settleAuditStr'] .= isset($auditRs[$v['settleAuditRs']]) ? ','.$auditRs[$v['settleAuditRs']] : '';
            }else{
                $v['settleAuditStr'] = isset($auditRs[$v['settleAuditRs']]) ? $auditRs[$v['settleAuditRs']] : '';
            }
            $list[$k] = $v;
        }
        return $list;
    }
    /**
     * 包装后查询列表,并以时间单位为键
     * @param mix $where
     * @return Ambigous
     */
    function getNewListByTimeUnit($where, $limit = NULL, $offset = NULL, $colum = '', $orderby = ''){
        $findList = $this->getList($where, $limit, $offset, $colum, $orderby);
        $list = array();
        foreach ($findList as $k => $v){
            $list[(int)$v['timeUnit']] = $v;
        }
        return $this->packing($list);
    }
    /**
     * 获取主流程列表，并以专营店ID为主键
     * @param array $where
     * @param string $limit
     * @param string $offset
     * @param string $colum
     * @param string $orderby
     * @return array
     */
    function getNewListByStoreId($where, $limit = NULL, $offset = NULL, $colum = '', $orderby = ''){
        $findList = $this->getList($where, $limit, $offset, $colum, $orderby);
        $list = array();
        foreach ($findList as $k => $v){
            $list[(int)$v['storeId']] = $v;
        }
        return $list;
    }
    /**
     * 初始化主流程数据
     * @param array $data
     */
    function initData($data = array()){
        if (!isset($data['storeId']) || !$data['storeId']){
            showError('请设置店铺ID');
        }
        if (!isset($data['year']) || !$data['year']){
            showError('请设置年份');
        }
        if (!isset($data['timeUnit']) || !$data['timeUnit']){
            showError('请设置时间');
        }
        $procId = $this->upset($data, array('createTime'=>time()));
        if ($procId){
            return $procId;
        }else{
            showError('生成失败');
        }
    }
    /**
     * 统计金额明细
     * @param int $procId 主线流程ID
     */
    function countMoneyDetail($procId){
        $intData = array(
            'budgetApply'=>0,//预算申请
            'budgetAudit'=>0,//预算审核
            'settleApply'=>0,//结算申请
            'settleAudit'=>0,//结算审核
        );
        //初始化
        $data = array(
            'online'   => $intData,
            'offline'       => $intData,
            'total'     => $intData
        );
        //区域营销基金-线上传播金额
        $this->CI->load->model('areaOnlineModel');
        $onlineMoney = $this->CI->areaOnlineModel->getMoney($procId);
        $data['online'] = $onlineMoney;
        //区域营销基金-营销活动
        $this->CI->load->model('areaOfflineModel');
        $offlineMoney = $this->CI->areaOfflineModel->getMoney($procId);
        $data['offline'] = $offlineMoney;
        //总计
        $data['total'] = array(
            'budgetApply' => $onlineMoney['budgetApply'] + $offlineMoney['budgetApply'],//预算申请
            'budgetAudit' => $onlineMoney['budgetAudit'] + $offlineMoney['budgetAudit'],//预算审核
            'settleApply' => $onlineMoney['settleApply'] + $offlineMoney['settleApply'],//结算申请
            'settleAudit' => $onlineMoney['settleAudit'] + $offlineMoney['settleAudit'],//结算审核
        );
        return $data;
    }
    /**
     * 更新金额
     * @param int $procId 主线流程ID
     */
    function updateMoney($procId){
        $findData = $this->getData($procId);
        $childMoney = $this->countMoneyDetail($procId);
        $data = array(
            'budgetApplyOnline' => $childMoney['online']['budgetApply'],
            'budgetApplyOffline' => $childMoney['offline']['budgetApply'],
            'budgetApplyTotal' => $childMoney['total']['budgetApply'],//预算申请
            'budgetAuditOnline' => $childMoney['online']['budgetAudit'],
            'budgetAuditOffline' => $childMoney['offline']['budgetAudit'],
            'budgetAuditTotal' => $childMoney['total']['budgetAudit'],//预算审核
            'settleApplyOnline' => $childMoney['online']['settleApply'],
            'settleApplyOffline' => $childMoney['offline']['settleApply'],
            'settleApplyTotal' => $childMoney['total']['settleApply'],//结算申请
            'settleAuditOnline' => $childMoney['online']['settleAudit'],
            'settleAuditOffline' => $childMoney['offline']['settleAudit'],
            'settleAuditTotal' => $childMoney['total']['settleAudit'],//结算审核
        );
        //双月额度
        $this->CI->load->model('importMoneyModel');
        $data['fixedMoney'] = $this->importMoneyModel->getMoney($findData['storeId'], $findData['timeUnit'], 21, $findData['year']);
        //上双月结转额度
        $data['preCarryMoney'] = $this->getPreCarryMoney($findData['storeId'], $findData['year'], $findData['timeUnit']);
        //可用额度
        $data['canUseMoney'] = $data['fixedMoney'] + $data['preCarryMoney'];
        //可结算金额
        $data['canSettleMoney'] = min($data['canUseMoney'], $data['settleAudit']);
        //结余金额
        $data['carryMoneyTotal'] = $data['canUseMoney'] - $data['canSettleMoney'];
        $data['carryMoneyTotal'] = $data['carryMoneyTotal'] > 0 ? $data['carryMoneyTotal'] : 0;
        //更新
        $this->edit($procId, $data);
        return true;
    }
    /**
     * 获取上双月结转额度
     * @param int $storeId 专营店ID
     * @param int $year 年份
     * @param int $timeUnit 时段
     * @return number
     */
    function getPreCarryMoney($storeId, $year, $timeUnit){
        $this->load->model('timeUnitModel');
        $preTimeUnitId = $this->timeUnitModel->getPreTimeUnit($year, $timeUnit);
        if ($preTimeUnitId){
            $preProcData = $this->getData(array('storeId'=>$storeId,'year'=>$year,'timeUnit'=>$preTimeUnitId));
            if ($preProcData){
                return (float)$preProcData['carryMoneyTotal'];
            }
        }
        return 0;
    }
    /**
     * 更新预算审核状态
     * @param number $id 项目ID
     * @return object
     */
    function budgetUpdateStatus($procId){
        return $this->edit($procId, array('budgetAuditRs'=>$this->getBudgetStatus($procId)));
    }
    /**
     * 获取项目预算审核状态值
     * @param int $procId
     * @return number
     */
    function getBudgetStatus($procId){
        $this->CI->load->model('areaOnlineModel');
        $this->CI->load->model('areaOfflineModel');
        $onlineStatusCount = $this->CI->areaOnlineModel->getBudgetStatusCount($procId);
        $offlineStatusCount = $this->CI->areaOfflineModel->getBudgetStatusCount($procId);
        $count = array(
            0 => $onlineStatusCount[0]+$offlineStatusCount[0],//未审核数
            1 => $onlineStatusCount[1]+$offlineStatusCount[1],//通过数
            2 => $onlineStatusCount[2]+$offlineStatusCount[2],//不通过数
        );
        $sumCount = array_sum($count);
        if($sumCount > 0){
            if ($count[0] == $sumCount){
                return 0;//未审核
            }elseif ($count[1] == $sumCount){
                return 1;//通过
            }elseif ($count[2] == $sumCount){
                return 2;//不通过
            }else{
                return 4;//部分通过
            }
        }else{
            return 0;
        }
    }
    /**
     * 更新结算审核状态
     * @param number $id 项目ID
     * @return object
     */
    function settleUpdateStatus($procId){
        $data['settleAuditRs'] = $this->getSettleStatus($procId);
        $data['settleAuditRs'] == 0 && $data['settleAuditRole'] = 0;
        return $this->edit($procId, $data);
    }
    /**
     * 统计结算审核数
     * @param number $procId
     */
    function getSettleStatusCount($procId){
        $this->CI->load->model('areaOnlineModel');
        $this->CI->load->model('areaOfflineModel');
        $onlineStatusCount = $this->CI->areaOnlineModel->getSettleStatusCount($procId);
        $offlineStatusCount = $this->CI->areaOfflineModel->getSettleStatusCount($procId);
        $count = array(
            -1 => $onlineStatusCount[-1]+$offlineStatusCount[-1],//未提交数
            0 => $onlineStatusCount[0]+$offlineStatusCount[0],//未审核数
            1 => $onlineStatusCount[1]+$offlineStatusCount[1],//通过数
            2 => $onlineStatusCount[2]+$offlineStatusCount[2],//不通过数
            3 => $onlineStatusCount[3]+$offlineStatusCount[3],//返回修改
        );
        return $count;
    }
    /**
     * 获取项目结算审核状态值
     * @param int $id
     */
    function getSettleStatus($procId){
        $count = $this->getSettleStatusCount($procId);
        $sumCount = array_sum($count);
        if($sumCount > 0){
            if ($count[0] == $sumCount){
                return 0;//未审核
            }elseif ($count[1] == $sumCount){
                return 1;//通过
            }elseif ($count[2] == $sumCount){
                return 2;//不通过
            }elseif ($count[3] == $sumCount){
                return 3;//返回修改
            }else{
                return 4;//部分通过
            }
        }else{
            return 0;
        }
    }
    /**
     * 分析列表，统计出条件专营店ID集的总和
     * @param array $sellpointIds 专营店id集
     * @param array $list 以专营店id为键的列表
     * @return array
     */
    function countTotalListByStoreIds($storeIds = array(),$list = array()){
        $data = array(
            'storeCount' => 0,//申请店数
            'fixedMoney' => 0,//固定额度（双月额度）
            'budgetApply'=>0,//预算申请
            'budgetAudit'=>0,//预算审核
            'settleApply'=>0,//结算申请
            'settleAudit'=>0,//结算审核
            'canSettleMoney' => 0,//可结算金额
            'settleMoney' => 0,//结算金额
            'finalSettleMoney' => 0,//最终结算金额
        );
        $filterStoreId = array_intersect($storeIds, array_keys($list));
        foreach ($filterStoreId as $storeId){
            if(isset($list[$storeId])){
                $data['storeCount'] ++;//申请店数累加
                $data['budgetApplyTotal']     += $list[$storeId]['budgetApplyTotal'];//预算申请
                $data['budgetAuditTotal']     += $list[$storeId]['budgetAuditTotal'];//预算审核
                $data['settleApplyTotal']       += $list[$storeId]['settleApplyTotal'];//结算申请
                $data['settleAuditTotal']       += $list[$storeId]['settleAuditTotal'];//结算审核
                $data['canSettleMoney']    += $list[$storeId]['canSettleMoney'];//最终结算金额
            }
        }
        return $data;
    }
}